package com.rookieCi.qrcodefile.sync;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.dlazaro66.qrcodereaderview.QRCodeReaderView;
import com.google.gson.Gson;
import com.lsjwzh.widget.materialloadingprogressbar.BuildConfig;
import com.rookieCi.qrcodefile.R;
import com.rookieCi.qrcodefile.TextActivity;
import com.rookieCi.qrcodefile.mode.NoteMode;
import com.rookieCi.qrcodefile.utils.CodeUtils;
import com.rookieCi.qrcodefile.utils.Logger;
import com.rookieCi.qrcodefile.utils.ZipUtils;
import com.xcc.myzxing.PointsOverlayView;

import butterknife.BindView;
import butterknife.ButterKnife;

public class AcceptFileActivity extends AppCompatActivity implements QRCodeReaderView.OnQRCodeReadListener, OnFileContactInterface {
    public int MY_PERMISSION_REQUEST_CAMERA = SendFileActivity.MY_PERMISSION_REQUEST_CAMERA;
    @BindView(R.id.image)
    public ImageView image;
    @BindView(R.id.layoutPreview)
    public ViewGroup layoutPreview;
    private AcceptFileContact fileContact;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_file);
        ButterKnife.bind(this);

        fileContact = new AcceptFileContact(this);

        image.postDelayed(this::openCamera, 100);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (qrCodeReaderView != null) {
            qrCodeReaderView.startCamera();
        }
    }

    @Override
    protected void onPause() {
        if (qrCodeReaderView != null) {
            qrCodeReaderView.stopCamera();
        }
        super.onPause();
    }

    private void openCamera() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            initQRCodeReaderView();
        } else {
            requestCameraPermission();
        }
    }

    private QRCodeReaderView qrCodeReaderView;
    private PointsOverlayView pointsOverlayView;

    private void initQRCodeReaderView() {
        View content = getLayoutInflater().inflate(R.layout.layout_send_content_decoder, layoutPreview, true);

        qrCodeReaderView = content.findViewById(R.id.qrdecoderview);
        pointsOverlayView = content.findViewById(R.id.points_overlay_view);

        qrCodeReaderView.setAutofocusInterval(2000L);
        qrCodeReaderView.setOnQRCodeReadListener(this);
        //qrCodeReaderView.setBackCamera();//后置摄像头
        qrCodeReaderView.setFrontCamera();
        qrCodeReaderView.startCamera();
    }

    private void requestCameraPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.cameraRequired)
                    .setNegativeButton(R.string.quxiao, null)
                    .setPositiveButton(R.string.queding, (dialog1, which) ->
                            ActivityCompat.requestPermissions(AcceptFileActivity.this
                                    , new String[]{Manifest.permission.CAMERA}, MY_PERMISSION_REQUEST_CAMERA))
                    .create();
            dialog.show();
        } else {
            Toast.makeText(this, R.string.myqx_qdksxtqx, Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSION_REQUEST_CAMERA);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode != MY_PERMISSION_REQUEST_CAMERA) return;
        if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            initQRCodeReaderView();
        } else {
            Toast.makeText(this, R.string.sxtqxbjj, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onQRCodeRead(String text, PointF[] points) {
        if (isDestroyed() || isFinishing()) return;
        pointsOverlayView.setPoints(points);
        Logger.out("扫码结果:" + text);
        if (fileContact.acceptText(text)) {
            int codeInt = fileContact.getCodeInt();
            if (codeInt == -1) {
                Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                vibrator.vibrate(100);//震动一下

                Intent intent = new Intent(this, TextActivity.class);
                int sendType = fileContact.getSendType();
                if (sendType == 3) {//文本
                    sendType = 1;
                    String acceptText = fileContact.getText();//接收到的文本
                    String unzip = ZipUtils.unzip(acceptText);
                    if (!TextUtils.isEmpty(unzip)) {
                        intent.putExtra("text", unzip);
                    }
                } else if (sendType == 1) {//文本
                    String acceptText = fileContact.getText();//接收到的文本
                    intent.putExtra("text", acceptText);
                } else {//文件
                    String filePath = fileContact.getFilePath();
                    intent.putExtra("text", filePath);
                }
                intent.putExtra("sendType", sendType);
                startActivity(intent);
                finish();
            } else {//反馈
                showCode();
            }
        }
    }

    private NoteMode noteMode;

    //显示二维码
    private void showCode() {
        if (noteMode == null) noteMode = new NoteMode();
        noteMode.idx = fileContact.getCodeInt() - 1;//编号已加1，此处减1
        noteMode.no = fileContact.getNo();
        noteMode.randomText();

        String json = new Gson().toJson(noteMode);
        try {
            Bitmap bitmap = new CodeUtils()
                    //.setEnd(codeMode.idx == -1)
                    .Create2DCode(json);
            image.setImageBitmap(bitmap);
        } catch (Exception e) {
            if (BuildConfig.DEBUG) e.printStackTrace();
        }
    }

    @Override
    public boolean checkFilePermissions() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0xFF01);
            return false;
        } else {
            //fileContact.openFile();
            return true;
        }
    }
}
